//
//  TestObject.m
//  NSThreadTest
//
//  Created by wangrui on 14-2-26.
//  Copyright (c) 2014年 Ourui. All rights reserved.
//

#import "TestObject.h"

@implementation TestObject

- (void)runTest{
    [NSThread detachNewThreadSelector:@selector(doSomethingOtherThread:) toTarget:self withObject:nil];
}

- (void)doSomethingOtherThread:(id)sender{
/*
    //测试一: 自动释放问题
    //结论:Thread创建时应该自己会创建一个autorealease pool，当要执行长时间的任务分配的对象很多时，要加@autoreleasepool
    //最好一般情况下都加
    
    @autoreleasepool { //不加或加autoreleasepool时Instrument测得内存先飙涨到160M后又降低到8M
        for (int i=0; i<1000000; i++) {
            NSArray *arr = [NSArray arrayWithObject:@"sting"];
            [arr description];
        }
    }
*/
    
    //测试二: 线程与runloop问题 及 autorelease 问题
    NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(time:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    [timer fire];
    
     [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    
    
    [self performSelectorOnMainThread:@selector(backToMainThread) withObject:nil waitUntilDone:NO];
}

- (void)time:(id)sender{
   
    NSLog(@"%d:timer event",[NSThread isMainThread]);
    
    //instrument 测得内存是成波形的。 说明每个runloop接受每个事件时会产生一个autorelease pool
    for (int i=0; i<100000; i++) {
        NSArray *arr = [NSArray arrayWithObject:@"sting"];
        [arr description];
    }
    
    static int count = 0;
    count++;
    if (count>10) {
        CFRunLoopStop([[NSRunLoop currentRunLoop] getCFRunLoop]);
    }
    
}

- (void)backToMainThread{
    NSLog(@"backToMainThread");
}


@end
